<?php

namespace DreamCat\FrameCore\HttpHandle;

use DreamCat\FrameInterface\HttpHandle\ErrorHandle;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Throwable;
use Zend\Diactoros\Response\TextResponse;

/**
 * 默认的异常处理对象
 * @author vijay
 */
class DefaultErrorHandle implements ErrorHandle
{
    /**
     * @Autowire
     * @var LoggerInterface 日志记录器
     */
    private $logger;
    /**
     * @Config errorhandle/msg
     * @var string 异常时的错误文本
     */
    private $errorMsg = "";
    /**
     * @Config errorhandle/code 500
     * @var int 异常时的错误码
     */
    private $errorCode = 500;

    /**
     * @return LoggerInterface 日志记录器
     */
    public function getLogger(): LoggerInterface
    {
        return $this->logger;
    }

    /**
     * @param LoggerInterface $logger 日志记录器
     * @return static 对象本身
     */
    public function setLogger(LoggerInterface $logger): DefaultErrorHandle
    {
        $this->logger = $logger;
        return $this;
    }

    /**
     * @param Throwable $throwable 捕获的异常
     * @return ResponseInterface 处理的响应对象
     */
    public function handle(Throwable $throwable): ResponseInterface
    {
        $this->getLogger()->error(
            $throwable->getMessage(),
            [
                "trace" => $throwable->getTraceAsString(),
                "file" => $throwable->getFile(),
                "line" => $throwable->getLine(),
                "code" => $throwable->getCode(),
            ]
        );
        return $this->errorResponse();
    }

    /**
     * @return ResponseInterface 异常时的响应信息
     */
    protected function errorResponse(): ResponseInterface
    {
        return new TextResponse($this->getErrorMsg(), $this->getErrorCode());
    }

    /**
     * @return string 异常时的错误文本
     */
    public function getErrorMsg(): string
    {
        return $this->errorMsg;
    }

    /**
     * @param string $errorMsg 异常时的错误文本
     * @return static 对象本身
     */
    public function setErrorMsg(string $errorMsg): DefaultErrorHandle
    {
        $this->errorMsg = $errorMsg;
        return $this;
    }

    /**
     * @return int 异常时的错误码
     */
    public function getErrorCode(): int
    {
        return $this->errorCode;
    }

    /**
     * @param int $errorCode 异常时的错误码
     * @return static 对象本身
     */
    public function setErrorCode(int $errorCode): DefaultErrorHandle
    {
        $this->errorCode = $errorCode;
        return $this;
    }
}

# end of file
